package com.film.service.impl.movie;

import com.alibaba.fastjson.JSONObject;
import com.film.service.movie.GetMoviesByClassService;
import com.film.utils.MySqlConnection;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Service
public class GetMoviesByClassServiceImpl implements GetMoviesByClassService {
    @Override
    public JSONObject getMovies(String className) throws SQLException {
        JSONObject resp = new JSONObject();
        List<JSONObject> items = new LinkedList<>();
        String sql = "select * from Movie where class = " + "'" + className + "'";
        Statement stmt = MySqlConnection.connect.createStatement();
        System.out.println(sql);
        ResultSet resultSet = stmt.executeQuery(sql);
        if (!resultSet.isBeforeFirst()) { //resultSet为空
            resp.put("error_message", "类别错误");
            return resp;
        }
        while (resultSet.next()) {
            JSONObject item = new JSONObject();
            String movieId = resultSet.getString("id");
            String name = resultSet.getString("name");
            String imgUrl = resultSet.getString("image");
            Integer stars = resultSet.getInt("stars");
            item.put("movieId", movieId);
            item.put("name", name);
            item.put("imgUrl", imgUrl);
            item.put("stars", String.valueOf(stars));
            items.add(item);
        }

        resp.put("movies", items);
        resp.put("movies_count", items.size());
        resultSet.close();
        stmt.close();
        return resp;
    }
}
